package com.ioufev.mqtt.utils;

public class HexUtils {

    /**
     * 将十六进制字符串转换为字节数组
     *
     * @param hexString 十六进制字符串
     * @return 字节数组
     * @throws IllegalArgumentException 如果输入无效
     */
    public static byte[] hexStringToByteArray(String hexString) {
        // 去除空格
        hexString = hexString.replaceAll("\\s", "");

        // 检查长度是否为偶数
        if (hexString.length() % 2 != 0) {
            throw new IllegalArgumentException("无效的十六进制字符串长度");
        }

        // 创建字节数组
        byte[] byteArray = new byte[hexString.length() / 2];

        // 逐对转换
        for (int i = 0; i < byteArray.length; i++) {
            int index = i * 2;
            int j = Integer.parseInt(hexString.substring(index, index + 2), 16);
            byteArray[i] = (byte) j;
        }

        return byteArray;
    }

    public static void main(String[] args) {
        String hexString = "2c e400 0d00 0401 6c8e 2ce4 000c 0003 016b 8b";
        try {
            byte[] byteArray = hexStringToByteArray(hexString);
            System.out.println("字节数组: " + java.util.Arrays.toString(byteArray));
        } catch (IllegalArgumentException e) {
            System.err.println("转换失败: " + e.getMessage());
        }
    }
}